package cn.cocho.android.mc.comp.button;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

import cn.cocho.android.mc.R;

public class BrightnessButton extends Button{
	
//	private final String BRIGHTNESS ="brightness";
	private int brightness=0;
	private boolean isGet=false;
	
	//*
	public BrightnessButton(Context context){
		super(context);
	}
	//*
	public BrightnessButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	
	public BrightnessButton(Context context, AttributeSet attrs) {
		super(context, attrs);
//		initAttributeValue(attrs);
		
		//*↑
		initAttributeValue(context,attrs);
	}
	
//	private void initAttributeValue(AttributeSet attrs){
//		brightness = attrs.getAttributeIntValue(CompUtils.NS_TBC, BRIGHTNESS, -60);
//	}
	
	//*↑
	private void initAttributeValue(Context context,AttributeSet attrs){
		TypedArray tdarr = context.obtainStyledAttributes(attrs, R.styleable.BrightnessButton);
		brightness = tdarr.getInt(R.styleable.BrightnessButton_brightness, -60);
		tdarr.recycle();
	}
	
	public StateListDrawable getStateListDrawable(Drawable normal) {	
		StateListDrawable listDrawable = new StateListDrawable();
		Bitmap srcBitmap = ((BitmapDrawable) normal).getBitmap();
		Bitmap bmp = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Config.ARGB_8888);
		ColorMatrix cMatrix = new ColorMatrix();
		cMatrix.set(new float[] { 1, 0, 0, 0, brightness, 0, 1, 0, 0, brightness,0 ,0, 1, 0, brightness, 0, 0, 0, 1, 0 });
		Paint paint = new Paint();
		paint.setColorFilter(new ColorMatrixColorFilter(cMatrix));
		Canvas canvas = new Canvas(bmp);
		// 在Canvas上绘制一个Bitmap
		canvas.drawBitmap(srcBitmap, 0, 0, paint);
		Drawable pressed = new BitmapDrawable(bmp);
		listDrawable.addState(new int[] { android.R.attr.state_pressed }, pressed);
		listDrawable.addState(new int[] { android.R.attr.state_selected }, pressed);
		listDrawable.addState(new int[] { android.R.attr.state_enabled }, normal);
		return listDrawable;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event){
		Drawable background=null;
		if (!isGet) {
			background=getBackground();
			isGet=true;
		}
		if (background != null) {
			setBackgroundDrawable(getStateListDrawable(background));
		}
		
		return super.onTouchEvent(event);
	}
	
}
